//
//  ADNewFeatureController.swift
//  myBlog
//
//  Created by mac2014 on 16/3/24.
//  Copyright © 2016年 AD. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
let newFeaturePageCount = 4
class ADNewFeatureController: UICollectionViewController {
    
    ///mark - properties
    //流水布局
    let layout = UICollectionViewFlowLayout()
    
    ///mark - system functions
    
    override func viewDidLoad() {
        super.viewDidLoad()
        prepareUI()
    }
    
    
    //创建一个layout
    init() {
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    ///mark - custum functions
    //layout设置
    func prepareUI() {
        layout.itemSize = UIScreen.mainScreen().bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.bounces = false
        collectionView?.pagingEnabled = true
        
        //注册cell
        self.collectionView!.registerClass(ADNewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }





    /// mark - UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return newFeaturePageCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        //得到可重用的cell，并转换成自定义的cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ADNewFeatureCell

        cell.backgroundColor = UIColor.yellowColor()
        //将cell的索引值相关联
        cell.index = indexPath.item
        
        return cell
    }
    
    //滚动的过程中得到相应的cell，并执行动画
    override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        //计算当前页码
        let page = Int(scrollView.contentOffset.x / view.bounds.width)
        
        //判断当前页是否是最后一页，并根据页码获得相应的cel
        if page == newFeaturePageCount - 1 {
            let index = NSIndexPath(forItem: page, inSection: 0)
            let cell = collectionView?.cellForItemAtIndexPath(index) as! ADNewFeatureCell
            
            cell.startBtnAnimation()
            
        }
    }
}
